package com.peycard.listener;

import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.peycard.common.util.BadConfigurationException;
import com.solab.iso8583.MessageFactory;
import com.solab.iso8583.parse.ConfigParser;

/**
 * Application Lifecycle Listener implementation class ISOListener
 *
 */
public class ISOListener implements ServletContextListener {

	private static Logger LOGGER = LoggerFactory.getLogger(ISOListener.class);
	
	private ISODaemon isoDaemon; 
	private Thread isoThread;
	private MessageFactory mfact;	
    /**
     * Default constructor. 
     */
    public ISOListener() {
        System.out.println("CREANDO UNA INSTANCIA DEL LISTENER DE CONTEXTO APRA WEB");
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
       isoThread.interrupt();
       isoDaemon.abort();
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent arg0) {
    	try {
			mfact = ConfigParser
			.createFromClasspathConfig("com/peycard/business/iso/config.xml");
		} catch (IOException e) {
			LOGGER.debug("NO SE PUEDE CONFIGURAR MSG FACTORY DESDE XML");
			throw new BadConfigurationException("NO SE PUEDE CONFIGURAR MSG FACTORY DESDE XML", e);
		} 
    	isoDaemon = new ISODaemon(mfact);
    	isoThread = new Thread(isoDaemon);    	    	
    	isoThread.start();    	
    }
	
}

